// pages/main/me/resume_editor/resume_editor.js
import { filter } from "../resume_detial/filter.js";
import { getLessLimitSizeImage } from '../resume_editor/index.js';
import { uploadFile } from  '../resume_editor/uploadAliyun/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showFreeTime:false,//显示空闲时间
    showSalaryType: false,//显示薪资类型
    count:6,//最大的上传数量
    code: 0,
    a:"",
    name: '',		//姓名
    gender: 0,		//性别
    birthday: '',		//出生年月
    contactNumber: '',	  //联系电话
    year: new Date().getFullYear(),//出生年月集合
    seekerInfo: null,//实名信息
    valueT: [18, 36],
    weekType: [
      { key: 'freeMon', name: "周一", state: false },
      { key: 'freeTue', name: "周二", state: false },
      { key: 'freeWed', name: "周三", state: false },
      { key: 'freeThur', name: "周四", state: false },
      { key: 'freeFri', name: "周五", state: false },
      { key: 'freeSta', name: "周六", state: false },
      { key: 'freeSun', name: "周日", state: false }],
    hours: ["00:00", "00:30", "01:00", "01:30", "02:00", "02:30", "03:00", "03:30", "04:00", "04:30", "05:00", "05:30",
      "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
      "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30",
      "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30"
    ],
    selectLists: {
      addressLists: [],//户籍所在地选择集合
      nationList: [],//民族
      educationLists: [
        { name: '小学', value: 1 },
        { name: '初中', value: 2 },
        { name: '中专/技校', value: 3 },
        { name: '高中', value: 4 },
        { name: '大专', value: 5 },
        { name: '本科及以上', value: 6 }
      ],//学历集合 教育程度0:不限 1:小学 2:初中 3:中专/技校 4:高中 5:大专 6:本科及以上
      workExperienceLists: [
        { name: '一年以下', value: 1 },
        { name: '1-3年', value: 2 },
        { name: '3-5年', value: 3 },
        { name: '5-10年', value: 4 },
        { name: '10年以上', value: 5 },
      ],//工作年限（1：一年以下 2:1-3年 3:3-5年 4:5-10年 5:10年以上
      expectWorkTypeLists: [
        { name: '全职', value: 1 },
        { name: '兼职', value: 2 },
        { name: '全职或兼职都看', value: 3 },
      ],//期望工作类型1：全职，2：兼职，3：全职或兼职
    },
    salaryForm: {
      type: 3, //3月 2 日 1时
      expectSalaryUpper: null,//最高薪资
      expectSalaryLower: null//最低薪资
    },
    selJob: [],//选择期望工作岗位
  },

  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    let that = this
    var codeA = '1';

    if(options.param){
      let opt = JSON.parse(options.param);
      codeA = opt.code;
    }else{
      codeA = options.code;
    }
    if (codeA) {
      console.log(codeA)
      this.setData({
        code: codeA,
      })
    }

    let title = ''
    if (codeA == 1) {
      title = '基本信息'
    } else if (codeA == 2) {
      title = '求职意向'
    } else if (codeA == 3) {
      title = '详细信息'
    }
    wx.setNavigationBarTitle({
      title: title
    })

    // 简历详情
    getApp().$http.getSeekerInfo().then(
      res => {
        console.log('创建简历')
        console.log(res)
        that.data.seekerInfo = res
        let arr = []
        if (that.data.seekerInfo.beforePositions && that.data.seekerInfo.beforePositions.length > 0) {
          that.data.seekerInfo.beforePositions.forEach((item, index) => {
            arr.push({ id: item.id, name: item.positionName })
          })
          that.data.seekerInfo.beforePositions = arr
        } else {
          that.data.seekerInfo.beforePositions = arr
        }
        res.photos = res.photos?res.photos.split(','):[]
        if(that.data.seekerInfo.expectPositions && that.data.seekerInfo.expectPositions.length>0){
          that.data.selJob = that.data.seekerInfo.expectPositions;
        }

        that.setData({
          name: res.name || "",
          gender: res.gender || 0,
          birthday: (new Date(res.birthday).getFullYear()) || 0,
          contactNumber: res.contactNumber ? res.contactNumber : res.phoneNumber,
          seekerInfo: res || null
        })
        console.log(that.data)
      }
    )
    //获取省
    getApp().$http.getAddressLists().then(res => {
      that.data.selectLists.addressLists = res;
      that.setData({
        selectLists: that.data.selectLists,
      })
      console.log(that.data)
    })
    //获取民族
    getApp().$http.getNationList().then(res => {
      that.data.selectLists.nationList = res;
      that.setData({
        selectLists: that.data.selectLists,
      })
      console.log(that.data)
    })
  },


  /**
    * 数据的双向绑定
    */
  inputedit(e) {
    console.log(e)
    let dataset = e.currentTarget.dataset;
    let value = e.detail.value;
    this.data[dataset.obj] = value;
    //obj是我们使用data-传递过来的键值对的键
    this.setData({
      [dataset.obj]: this.data[dataset.obj]
    })
    console.log(this.data);
  },

  /**
  * 改变性别
  */
  changeGender(e) {
    let dataset = e.currentTarget.dataset;
    this.data[dataset.name] = parseInt(dataset.value);
    this.setData({
      [dataset.name]: this.data[dataset.name]
    })
    console.log(this.data);
  },
  /**
   * 改变身份
   */
  changeIdentity(e) {
    let dataset = e.currentTarget.dataset;
    let isStudent = dataset.value === 'true' ? true : false;
    let seekerInfoA = this.data.seekerInfo;
    seekerInfoA['isStudent'] = isStudent;
    this.setData({
      seekerInfo: seekerInfoA
    })
    console.log(this.data);
  },

  /**
   * 改变有无健康证
   */
  changeHaveHealthCertificate(e) {
    let dataset = e.currentTarget.dataset;
    let isHaveHealthCertificate = dataset.value === 'true' ? true : false;
    let seekerInfoA = this.data.seekerInfo;
    seekerInfoA['isHaveHealthCertificate'] = isHaveHealthCertificate;
    this.setData({
      seekerInfo: seekerInfoA
    })
    console.log(this.data);
  },

   /**
   * 改变有无社保
   */
  changeSocialInsurance(e) {
    let dataset = e.currentTarget.dataset;
    let haveSocialInsurance = dataset.value === 'true' ? true : false;
    let seekerInfoA = this.data.seekerInfo;
    seekerInfoA['haveSocialInsurance'] = haveSocialInsurance;
    this.setData({
      seekerInfo: seekerInfoA
    })
    console.log(this.data);
  },
  
  /**
   * 改变身高
   */
  changeHeight(e) {
    let dataset = e.currentTarget.dataset;
    let height = e.detail.value;
    let seekerInfoA = this.data.seekerInfo;
    seekerInfoA['height'] = height;
    this.setData({
      seekerInfo: seekerInfoA
    })
    console.log(this.data);
  },

  // 公用的选择器事件
  changeFun: function (e) {
    let dataset = e.currentTarget.dataset;
    let code = dataset.code;
    let value = parseInt(e.detail.value);
    let selectDict = this.data.selectLists;
    let seekerInfoA = this.data.seekerInfo;
    if (code === 1) {
      // 选择年份
      this.setData({
        birthday: value,
      })
    } else if (code === 2) {
      let name = selectDict.addressLists[value].name;
      seekerInfoA['nativePlace'] = name;
      this.setData({
        seekerInfo: seekerInfoA
      })
    } else if (code === 3) {
      let name = selectDict.nationList[value].name;
      seekerInfoA['ethnicity'] = name;
      this.setData({
        seekerInfo: seekerInfoA
      })
    } else if (code === 4) {
      let edu = selectDict.educationLists[value];
      seekerInfoA['education'] = edu.value;
      this.setData({
        seekerInfo: seekerInfoA
      })
    } else if (code === 5) {
      let workE = selectDict.workExperienceLists[value];
      seekerInfoA['workExperience'] = workE.value;
      this.setData({
        seekerInfo: seekerInfoA
      })
    } else if (code === 6) {
      let workT = selectDict.expectWorkTypeLists[value];
      seekerInfoA['expectWorkType'] = workT.value;
      this.setData({
        seekerInfo: seekerInfoA
      })
    }
  },

  // 空闲时间弹出
  clickFreeTime(){
    console.log('选择空闲时间')
    this.setData({
      showFreeTime: true
    })
  },

    // 选择空闲周
    selectWeekType(e){
      let dataset = e.currentTarget.dataset;
      let index = dataset.index;
      this.data.weekType[index].state = !this.data.weekType[index].state;
      this.setData({
        weekType: this.data.weekType
      })
    },

  // 选择空闲时间
  okFunTime(e){
    let dataset = e.currentTarget.dataset;
    let name = dataset.name;
    console.log(name)
    if(name === "ok"){
      let seekerInfoA = this.data.seekerInfo;
      this.data.weekType.forEach((item,index)=>{
        seekerInfoA[item.key] = item.state
      }),
      seekerInfoA['freeStartTime'] = this.data.hours[this.data.valueT[0]],
      seekerInfoA['freeEndTime'] = this.data.hours[this.data.valueT[1]],
      
      this.setData({
        seekerInfo: seekerInfoA,
      })

    }
    this.setData({
      showFreeTime: false
    })
    console.log("点击了完成")

  },

  // 选择空闲时间
  bindChangeT(e){
    let dataset = e.currentTarget.dataset;
    let name = e.detail.value;
    console.log(name)
    this.setData({
      valueT: name,
    })

  },  

  // 期望薪资设置完成
  okFunSalary(e){
    let dataset = e.currentTarget.dataset;
    let name = dataset.name;
    console.log(name)
    if(name === "ok"){    
      let seekerInfoA = this.data.seekerInfo;
      seekerInfoA.expectSalaryUnit = this.data.salaryForm.type;  

      if (seekerInfoA.expectSalaryUnit === 3) {
        seekerInfoA.expectSalaryLower = this.data.salaryForm.expectSalaryLower;
        seekerInfoA.expectSalaryUpper = this.data.salaryForm.expectSalaryUpper;
      }else{
        seekerInfoA.expectSalaryLower = this.data.salaryForm.expectSalaryUpper;
        seekerInfoA.expectSalaryUpper = this.data.salaryForm.expectSalaryUpper;
      }

      this.setData({
        seekerInfo: seekerInfoA,
      })

    }
    this.setData({
      showSalaryType: false
    })
    console.log("点击了完成")
  },

  // 切换薪资类型
  selectSalaryType(e){
    let dataset = e.currentTarget.dataset;
    let type = parseInt(dataset.type);
    let dict = this.data.salaryForm;
    dict.type = type;
    this.setData({
      salaryForm: dict,
    })
  },

  /**
    * salary数据的双向绑定
    */
   salaryInputedit(e) {
    let dataset = e.currentTarget.dataset;
    let value = e.detail.value;
    let dict = this.data.salaryForm;
    dict[dataset.obj] = value;
    this.setData({
      salaryForm: dict
    })
    console.log(this.data.salaryForm);
  },
 /**
    * 期望工作岗位
    */
   goSelectItem(e) {
    getApp().$routes.goTo(getApp().$routes.selectPosition, {
      "selJob": this.data.selJob,
    });
  },
  

  // 期望薪资
  getExpectedSalary(){
    if(!this.data.seekerInfo.expectWorkType){
        wx.showToast({
            icon:'none',title:'请先选择期望工作类型'
        })
        return false
    }

    if(this.data.seekerInfo.expectWorkType != 2){
        this.data.salaryForm.type = 3
    }else{
        this.data.salaryForm.type = 1
    }
    this.data.salaryForm.type = this.data.seekerInfo.expectSalaryUnit?this.data.seekerInfo.expectSalaryUnit:this.data.salaryForm.type
    this.data.salaryForm.expectSalaryLower = this.data.seekerInfo.expectSalaryLower?this.data.seekerInfo.expectSalaryLower:null
    this.data.salaryForm.expectSalaryUpper = this.data.seekerInfo.expectSalaryUpper?this.data.seekerInfo.expectSalaryUpper:null
    this.setData({
      showSalaryType: true
    })
  },

  // 删除图片
  deleteimg(e){
    let dataset = e.currentTarget.dataset;
    let index = parseInt(dataset.index);
    var seekerInfoA = this.data.seekerInfo;
    seekerInfoA.photos.splice(index,1);
    this.setData({
      seekerInfo: seekerInfoA,
    })
  },

  // 选择图片
  chooseImg(){
    let that = this
    wx.chooseImage({
        count: that.count - that.data.seekerInfo.photos.length, //可以上传多少张
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
            let tempFilePaths = res.tempFilePaths;
            for (let i = 0; i < tempFilePaths.length;i++){
                let filePath = tempFilePaths[i];
                getLessLimitSizeImage(`pressCanvas_${i}`, filePath, that.imageSize, that.windowWidth, (path) => {
                    wx.showLoading({
                        title:'上传中，请稍等~'
                    })
                    filePath = path;
                    uploadFile({
                        filePath: filePath,
                        dir: 'resumephoto'
                    })
                    .then(res => {
                        wx.hideLoading()

                        // data.photos = data.photos?data.photos.split(','):[]
                        // this.seekerInfo = data
                        // this.$set(this.seekerInfo,'photos',name)
                        let seekerInfoA = that.data.seekerInfo;
                        seekerInfoA.photos.push(res.aliyunFileKey);
                        that.setData({
                          seekerInfo: seekerInfoA
                        })
                        console.log(seekerInfoA.photos);

                        // if(!(this.count - this.form.ossImgList.length)){
                        //     this.plusimgs = false
                        // }
                    })
                    .catch(err => { console.log('upload fail', err) })
                    .finally(() => {
                    })
                })
            }
        },
    })
  },

  // 保存简历信息 需要根据不同的 code 来判断
  saveForm(){
    let obj = this.checkForm()
    console.log(obj)
    if(obj){
        // 不是需要编辑求职意向的的时候 不需要更改新增单位的时候
        if(this.data.code !== '2'){
            obj.expectSalaryLower = -1 //跳过薪资区间
            obj.expectSalaryUpper = -1
        }

        // code 为 1 或者 2的时候 要把  曾经做过  和 个人照片 带上 不要被清空 坑
        if(this.data.code == '1' || this.data.code == '2'){
            obj.photos = this.data.seekerInfo.photos.toString()
            let arr = []
            if(this.data.seekerInfo.beforePositions && this.data.seekerInfo.beforePositions.length >0 ){
                this.data.seekerInfo.beforePositions.forEach((item,index)=>{
                    arr.push({id:item.id,name:item.positionName})
                })
                obj.beforePositions = arr
            }else{
                obj.beforePositions = arr
            }
        }

        getApp().$http.saveSeekerInfo(obj).then(res=>{
          wx.showToast({
              title: '修改成功',
              icon: 'none'
          })
          setTimeout(()=>{
              wx.navigateBack()
          },1000)
        })
    }
  },


  // 公用表单校验器
  checkForm() {

    let data = this.data.seekerInfo;
    if (this.data.code === '1') {
      // 基本信息
      if (!data.name || data.name.length < 2 || data.name.length > 40) {
        wx.showToast({
          icon: 'none', title: '姓名应为2-20个汉字或4-40个字母'
        })
        return false
      } else if (!data.gender) {
        wx.showToast({
          icon: 'none', title: '请选择性别'
        })
        return false
      } else if (!data.birthday) {
        wx.showToast({
          icon: 'none', title: '请选择生日年份'
        })
        return false
      } else if (!data.contactNumber || data.contactNumber.length != 11) {
        wx.showToast({
          icon: 'none', title: '请填写联系电话且必须是11位手机号'
        })
        return false
      } else if (!data.nativePlace) {
        wx.showToast({
          icon: 'none', title: '请选择户籍所在地'
        })
        return false
      } else if (!data.ethnicity) {
        wx.showToast({
          icon: 'none', title: '请选择民族'
        })
        return false
      } else if (!data.education) {
        wx.showToast({
          icon: 'none', title: '请选择学历'
        })
        return false
      } else if (!data.workExperience) {
        wx.showToast({
          icon: 'none', title: '请选择工作年限'
        })
        return false
      } else if (data.isStudent !== false && data.isStudent !== true) {
        wx.showToast({
          icon: 'none', title: '请选择身份'
        })
        return false
      } else if (data.isHaveHealthCertificate !== false && data.isHaveHealthCertificate !== true) {
        wx.showToast({
          icon: 'none', title: '请选择有无健康证'
        })
        return false
      } else {
        // 封装 基本信息的数据集合
        let obj = {
          name: this.data.name,
          gender: this.data.gender,
          birthday: new Date().setFullYear(this.data.birthday,6,6),
          contactNumber: this.data.contactNumber,
          nativePlace: data.nativePlace,
          ethnicity: data.ethnicity,
          education: data.education,
          workExperience: data.workExperience,
          isStudent: data.isStudent,
          isHaveHealthCertificate: data.isHaveHealthCertificate
        }
        if (data.height) {
          obj.height = data.height
        }
        return obj
      }

    } else if (this.data.code === '2') {
      // 求职意向
      let obj = {
        name: this.data.name,
        gender: this.data.gender,
        birthday: new Date().setFullYear(this.data.birthday,6,6),
        contactNumber: this.data.contactNumber,
      }

      data.expectSalaryUpper = data.expectSalaryUpper ? Number(data.expectSalaryUpper) : false
      data.expectSalaryLower = data.expectSalaryLower ? Number(data.expectSalaryLower) : false

      // console.log(data.expectSalaryUnit)

      if (!data.expectWorkType) {
        wx.showToast({
          icon: 'none', title: '请选择期望岗位类型'
        })
        return false
      } else if ((data.expectPositions && data.expectPositions.length < 1) || !data.expectPositions) {
        wx.showToast({
          icon: 'none', title: '请选择期望岗位'
        })
        return false
      }
      // else if(!data.expectSalaryUpper || !data.expectSalaryLower){
      // 	wx.showToast({
      // 		icon:'none',title:'薪资必填'
      // 	})
      // 	return false
      // }
      // else if(!data.expectSalaryUnit){
      // 	wx.showToast({
      // 		icon:'none',title:'薪资单位必选'
      // 	})
      // 	return false
      // }

      // 如果 薪资 都填了的话
      if (data.expectSalaryUpper && data.expectSalaryLower) {

        if (!data.expectSalaryUnit) {
          wx.showToast({
            icon: 'none', title: '薪资单位必选'
          })
          return false
        }

        if (data.expectSalaryUnit == 3) {
          if ((data.expectSalaryUpper > 30000 || data.expectSalaryUpper < 850) || (data.expectSalaryLower > 30000 || data.expectSalaryLower < 850) || data.expectSalaryLower > data.expectSalaryUpper) {
            wx.showToast({
              icon: 'none', title: '最低薪资不得小于850，最大薪资不得大于30000'
            })
            return false
          }
        }

        if (data.expectSalaryUnit == 2) {
          if (data.expectSalaryUpper < 40 || data.expectSalaryUpper > 3000) {
            wx.showToast({
              icon: 'none', title: '薪资必须在40-3000之间'
            })
            return false
          }
        }

        if (data.expectSalaryUnit == 1) {
          if (data.expectSalaryUpper < 10 || data.expectSalaryUpper > 100) {
            wx.showToast({
              icon: 'none', title: '薪资必须在10-100之间'
            })
            return false
          }
        }

        obj.expectSalaryLower = data.expectSalaryLower
        obj.expectSalaryUpper = data.expectSalaryUpper
      }

      // 计算岗位
      if (data.expectPositions && data.expectPositions.length > 0) {
        let arr = []
        data.expectPositions.forEach((item, index) => {
          arr.push({ id: item.id, name: item.positionName })
        })
        obj.expectPositions = arr
      }

      obj.expectSalaryUnit = data.expectSalaryUnit
      obj.expectWorkType = data.expectWorkType

      // 计算 空闲时间 兼职的时候才有空闲时间
      if (data.expectWorkType === 2) {

        let num_time = 0
        this.data.weekType.forEach((item, index) => {
          if (data[item.key]) {
            num_time++;
          }
        })

        if (!num_time) {
          wx.showToast({
            icon: 'none', title: '空闲时间必选'
          })
          return false
        } else if (!data.freeEndTime || !data.freeStartTime) {
          wx.showToast({
            icon: 'none', title: '空闲时间开始结束时间必选'
          })
          return false
        } else {
          this.data.weekType.forEach((item, index) => {
            if (item.state) {
              obj[item.key] = true
            }
          })

          obj.freeEndTime = data.freeEndTime
          obj.freeStartTime = data.freeStartTime
        }

      }

      return obj

    } else if (this.data.code === '3') {
      // 详细信息

      let num = 0

      let obj = {
        name: this.data.name,
        gender: this.data.gender,
        birthday: new Date().setFullYear(this.data.birthday,6,6),
        contactNumber: this.data.contactNumber,
      }

      let arr = []
      if (data.beforePositions && data.beforePositions.length > 0) {
        data.beforePositions.forEach((item, index) => {
          arr.push({ id: item.id, name: item.positionName })
        })
        obj.beforePositions = arr
        num++
      } else {
        obj.beforePositions = arr
      }

      if (data.haveSocialInsurance === false || data.haveSocialInsurance === true) {
        obj.haveSocialInsurance = data.haveSocialInsurance
        num++
      }

      if (data.photos && data.photos.length > 0) {
        obj.photos = data.photos.toString();
        num++
      } else {
        obj.photos = ''
      }

      if (num) {
        return obj
      } else {
        wx.showToast({
          icon: 'none', title: '至少完善一项信息'
        })
        return false
      }


    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let jobs = this.data.selJob
    if(jobs.length>0){
      console.log(jobs);
      let seekerInfoA = this.data.seekerInfo;
      seekerInfoA.expectPositions = jobs;
      this.setData({
        seekerInfo: seekerInfoA
      })
      console.log(this.data.seekerInfo.expectPositions)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})